import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../model/health_record.dart';
import '../model/reminder.dart';
import '../service/database_service.dart';
import 'base_record_dialog.dart';

class AddVaccineRecordDialog extends BaseRecordDialog {
  const AddVaccineRecordDialog({Key? key, required String babyId})
    : super(key: key, babyId: babyId);

  @override
  _AddVaccineRecordDialogState createState() => _AddVaccineRecordDialogState();
}

class _AddVaccineRecordDialogState
    extends BaseRecordDialogState<AddVaccineRecordDialog> {
  final _nameController = TextEditingController();
  final _hospitalController = TextEditingController();
  DateTime? _nextDoseDate;
  bool _hasNextDose = false;

  @override
  void dispose() {
    _nameController.dispose();
    _hospitalController.dispose();
    super.dispose();
  }

  @override
  String getDialogTitle() => '记录疫苗';

  @override
  Widget buildCustomContent(BuildContext context) {
    return Column(
      children: [
        TextField(
          controller: _nameController,
          decoration: InputDecoration(
            labelText: '疫苗名称',
            border: OutlineInputBorder(),
          ),
        ),
        SizedBox(height: 16),
        TextField(
          controller: _hospitalController,
          decoration: InputDecoration(
            labelText: '接种医院',
            border: OutlineInputBorder(),
          ),
        ),
        SwitchListTile(
          title: Text('需要下次接种'),
          value: _hasNextDose,
          onChanged: (value) {
            setState(() => _hasNextDose = value);
          },
        ),
        if (_hasNextDose) ...[
          ListTile(
            title: Text('下次接种日期'),
            trailing: TextButton(
              child: Text(
                _nextDoseDate != null
                    ? DateFormat('yyyy-MM-dd').format(_nextDoseDate!)
                    : '选择日期',
              ),
              onPressed: () async {
                final date = await showDatePicker(
                  context: context,
                  initialDate: DateTime.now().add(Duration(days: 30)),
                  firstDate: DateTime.now(),
                  lastDate: DateTime.now().add(Duration(days: 365)),
                );
                if (date != null) {
                  setState(() => _nextDoseDate = date);
                }
              },
            ),
          ),
        ],
      ],
    );
  }

  @override
  Future<void> saveRecord(BuildContext context) async {
    if (_nameController.text.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请输入疫苗名称')));
      return;
    }

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.vaccine,
          timestamp: selectedDateTime,
          data: {
            'name': _nameController.text,
            'hospital': _hospitalController.text,
            'hasNextDose': _hasNextDose,
            'nextDoseDate': _nextDoseDate?.toIso8601String(),
            'notes': notes,
          },
        ),
      );

      // 如果设置了下次接种日期，创建提醒
      if (_hasNextDose && _nextDoseDate != null) {
        // await DatabaseService().addReminder(
        //   Reminder(
        //     id: 0,
        //     babyId: widget.babyId,
        //     title: '疫苗接种提醒：${_nameController.text}',
        //     type: ReminderType.vaccine,
        //     scheduleTime: _nextDoseDate!,
        //   ),
        // );
      }

      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
    }
  }
}
